#include <iostream>
#include <pthread.h> // 编译时需要连接pthread库
#include <unistd.h>

class Request
{
public:
    Request(int start, int end, const std::string &threadName) 
        :_start(start), _end(end), _threadName(threadName)
    {}

public:
    int _start;
    int _end;
    std::string _threadName;
};

class Response
{
public:
    Response(int result, int exitcode) :_result(result), _exitCode(exitcode)
    {} 

public:
    int _result;  // 计算结果
    int _exitCode;  // 计算结果是否可靠
};

// 可以被多个执行流同时执行, show函数被重入。写该函数只为举例说明
void show(const std::string &name)
{
    std::cout << name << " say# ";
}

void *sumCount(void *args) // 线程的参数和返回值，不仅仅可以用来进行传递一般参数，也可以传递对象!!!
{
    Request *rq = static_cast<Request*>(args);  // Request *rq = (Request*)args;
    Response *rsp = new Response(0,0);
    
    for (int i = rq->_start; i <= rq->_end; ++i)
    {
        show(rq->_threadName);
        std::cout << " is running, calculating..., " << i << std::endl;
        rsp->_result += i;
        usleep(100000);  //0.1s
    }

    return rsp;
}
int main()
{
    pthread_t tid;
    Request *rq = new Request(1, 100, "thread 1");
    pthread_create(&tid, nullptr, sumCount, rq);

    void* ret;
    pthread_join(tid, &ret); // 线程的参数和返回值，不仅仅可以用来进行传递一般参数，也可以传递对象！！
    Response *rsp = static_cast<Response*>(ret);
    std::cout << "rsp->result: " << rsp->_result << ", exitcode: " << rsp->_exitCode << std::endl;

    delete rsp;
    delete rq;

    return 0;
}